package com.epalmpay.service.shop.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.epalmpay.bean.ShopDetailBean;
import com.epalmpay.dto.activity.ActivitySelectiveListOutDTO;
import com.epalmpay.dto.activity.ActivitySelectiveOutDTO;
import com.epalmpay.dto.agent.AgentInDTO;
import com.epalmpay.dto.agent.AgentInfoOutDTO;
import com.epalmpay.dto.agent.AgentListOutDTO;
import com.epalmpay.dto.agent.AgentNetInDTO;
import com.epalmpay.dto.mall.MallGoodListOutDTO;
import com.epalmpay.dto.member.BalanceInDTO;
import com.epalmpay.dto.member.MemberOutDTO;
import com.epalmpay.dto.merchantmanage.GroupInDTO;
import com.epalmpay.dto.merchantmanage.GroupListOutDTO;
import com.epalmpay.dto.merchantmanage.GroupOutDTO;


import com.epalmpay.dto.shopuser.ShopCashierInDTO;
import com.epalmpay.dto.shopuser.ShopCashierListOutDTO;
import com.epalmpay.dto.system.*;
import com.epalmpay.entity.*;
import com.epalmpay.entity.Response;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.util.*;
import org.apache.shiro.crypto.hash.SimpleHash;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.enumdef.BizEnum.UserStatus;
import com.epalmpay.mapper.AgentMapper;
import com.epalmpay.mapper.CrcodeMapper;
import com.epalmpay.mapper.DeviceMapper;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.ShopGroupRelationMapper;
import com.epalmpay.mapper.ShopMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.mapper.UserbaseMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.MerchantRegister;
import com.epalmpay.payplat.MerchantUpdate;
import com.epalmpay.payplat.PayBalanceChange;
import com.epalmpay.payplat.PayBalanceQuery;
import com.epalmpay.payplat.PayUserLevel;
import com.epalmpay.payplat.result.PayBalanceResult;
import com.epalmpay.payplat.result.PayLevelBean;
import com.epalmpay.payplat.result.PayLevelResult;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.shop.IShopService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.usercenter.UserAuthApi;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;

import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;

@Service("shopService")
public class ShopServiceImpl implements IShopService {

    @Resource
    private UserbaseMapper userbaseMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private AgentMapper agentMapper;
    @Resource
    private TradeOfflineMapper tradeOfflineMapper;

    @Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private CrcodeMapper crcodeMapper;

    @Autowired
    protected WxService wxService;
    @Autowired
    protected IWxBaseService wxBaseService;
    @Autowired
    @Lazy
    private ITemplateMailSendService templateMailSendService;

    @Resource
    private IWalletService walletService;
    protected Logger logger = Logger.getLogger(this.getClass());

    @Override
    public ShopListOutDTO listShop(ShopInDTO shopInDTO, PageDTO pageDTO) throws ApplicationException {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        ArrayList<ShopOutDTO> shopOutList = new ArrayList<ShopOutDTO>();
        Shop shop = new Shop();
        Page page = Tools.pageEmtity(pageDTO);
        shop.setPage(page);
        Userbase userbase = new Userbase();
        userbase.setGroupId(shopInDTO.getGroupId());
        try {
            shop.setUserbase(userbase);
            shop.setStatus(shopInDTO.getStatus());
            shop.setLastEnd(shopInDTO.getLastLoginEnd());
            shop.setLastStart(shopInDTO.getLastLoginStart());
            shop.setAgentId(shopInDTO.getAgentId());
            shop.setIndustryId(shopInDTO.getIndustryId());
            shop.setMerchantId(shopInDTO.getMerchantId());
            shop.setMerchantName(shopInDTO.getMerchantName());
            shop.setDeviceStatus(shopInDTO.getDeviceStatus());
            List<Shop> listShop = shopMapper.shoplistPage(shop);
            for (int i = 0; i < listShop.size(); i++) {
                ShopOutDTO shopOutDTO = new ShopOutDTO();
                PropertyCopyUtil.copyPropertiesExclude(listShop.get(i), shopOutDTO);
                shopOutDTO.setIndustryName(listShop.get(i).getIndustryType().getName());
                shopOutDTO.setStatus(listShop.get(i).getShopGroupApprove().getStatus());
                shopOutDTO.setAgentName(listShop.get(i).getAgent().getMerchantName());
                shopOutDTO.setBigBusiness(listShop.get(i).getGroup().getMerchantName());
                shopOutDTO.setPayMerchantCode(listShop.get(i).getShopGroupRelation().getPayMerchantCode());
                shopOutDTO.setTagentId(listShop.get(i).getAgentId());
                shopOutList.add(shopOutDTO);
                shopListOutDTO.setShopOutDTOList(shopOutList);
            }
            shopListOutDTO.setPage(page);
            shopListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
            return shopListOutDTO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public ShopSelectiveListOutDTO shopSelective(ShopSelectiveQueryDTO shopSelectiveQueryDTO) {
        ShopSelectiveListOutDTO shopSelectiveOutDTOList = new ShopSelectiveListOutDTO();
        List<ShopSelectiveOutDTO> shopSelectiveOutDTOList1 = new ArrayList<ShopSelectiveOutDTO>();

        if (shopSelectiveQueryDTO.getAgentId() != null) {
            List<Agent> agents = agentMapper.getAllSubAgentByAgentId(shopSelectiveQueryDTO.getAgentId(), shopSelectiveQueryDTO.getGroupId());
            StringBuffer buffer = new StringBuffer("" + shopSelectiveQueryDTO.getAgentId());
            if (agents.size() > 0) {
                for (Agent agent : agents) {
                    buffer.append(",").append(agent.getId());
                }
                shopSelectiveQueryDTO.setAgentIds(buffer.toString());
            }
        }
        Long total = shopMapper.countListByQuery(shopSelectiveQueryDTO);
        shopSelectiveOutDTOList.setTotal(total);
        List<Map> resultSet = shopMapper.listByQuery(shopSelectiveQueryDTO);
        if (resultSet != null) {
            for (int i = 0; i < resultSet.size(); i++) {
                ShopSelectiveOutDTO shopSelectiveOutDTO = new ShopSelectiveOutDTO();
                shopSelectiveOutDTO.setId(Long.parseLong(resultSet.get(i).get("id").toString()));
                shopSelectiveOutDTO.setAgentName((String) resultSet.get(i).get("agent_name"));
                shopSelectiveOutDTO.setIndustryName((String) resultSet.get(i).get("name"));
                shopSelectiveOutDTO.setMerchantName((String) resultSet.get(i).get("merchant_name"));
                shopSelectiveOutDTOList1.add(shopSelectiveOutDTO);
            }
            shopSelectiveOutDTOList.setShopSelectiveOutDTOList(shopSelectiveOutDTOList1);
        }
        return shopSelectiveOutDTOList;
    }

    @Override
    public List<Map<String, String>> getNonemptyAgent(Long groupId) {
        return shopMapper.getNonemptyAgent(groupId);
    }

    @Override
    public List<Map<String, String>> getNonemptyIndustry(Long groupId) {
        return shopMapper.getNonemptyIndustry(groupId);
    }

    @Override
    public List<Map> getShopListById(ShopDetailBean shopDetailBean) {
        return shopMapper.getShopListByIdAndAgentId(shopDetailBean.getGroupId(), shopDetailBean.getAgentId(), shopDetailBean.getShopIds());
        //return shopMapper.getShopListById(shopIdList);
    }

    @Override
    public List<Map> getShopListById2(List shopIdList, Long activityId) {
        return shopMapper.getShopListById2(shopIdList, activityId);
    }

    @Override
    public ShopListOutDTO rate(Long groupId, Byte type) throws ApplicationException {
        ArrayList<ShopOutDTO> shopOutList = new ArrayList<ShopOutDTO>();
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        Group group = groupMapper.selectByPrimaryKey(groupId);
        if (group != null) {
            String groupIdCode = group.getPayGroupCode();
            // 支付平台查询商户等级
            PayUserLevel ul = PayUserLevel.initialize(groupIdCode);
            PayLevelResult payLevelResult = IPayAPI.queryUserLevel(ul);
            if (!PayResult.SUCCESS.equals(payLevelResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, payLevelResult.getRespCode() + "#" + payLevelResult.getMsgTxt());
            }
            Byte type1 = 3;// 2表示用户3表示 商户
            List<PayLevelBean> list = payLevelResult.getLeves();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getType().equals(type1)) {
                    ShopOutDTO shopOutDTO = new ShopOutDTO();
                    shopOutDTO.setLeveId(list.get(i).getLeveId());
                    shopOutDTO.setLeveName(list.get(i).getLeveName());
                    shopOutList.add(shopOutDTO);
                    shopListOutDTO.setShopOutDTOList(shopOutList);
                }
            }

        }
        return shopListOutDTO;
    }

    @Override
    public ShopListOutDTO memberRate(Long groupId, Byte type) throws ApplicationException {
        ArrayList<ShopOutDTO> shopOutList = new ArrayList<ShopOutDTO>();
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        Group group = groupMapper.selectByPrimaryKey(groupId);
        if (group != null) {
            String groupIdCode = group.getPayGroupCode();
            // 支付平台查询商户等级
            PayUserLevel ul = PayUserLevel.initialize(groupIdCode);
            PayLevelResult payLevelResult = IPayAPI.queryUserLevel(ul);
            if (!PayResult.SUCCESS.equals(payLevelResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, payLevelResult.getRespCode() + "#" + payLevelResult.getMsgTxt());
            }
            Byte type1 = 2;// 2表示用户3表示 商户
            List<PayLevelBean> list = payLevelResult.getLeves();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getType().equals(type1)) {
                    ShopOutDTO shopOutDTO = new ShopOutDTO();
                    shopOutDTO.setLeveId(list.get(i).getLeveId());
                    shopOutDTO.setLeveName(list.get(i).getLeveName());
                    shopOutList.add(shopOutDTO);
                    shopListOutDTO.setShopOutDTOList(shopOutList);
                }
            }

        }
        return shopListOutDTO;
    }

    @Override
    public Boolean saveshop(ShopInDTO shopInDTO) throws ApplicationException {
        //根据地址查询经纬度
        String detailed = shopInDTO.getProvinceCityDistrict() + shopInDTO.getAddress();
        String result = HttpClientUtil.get(Const.GEOCODER + "?=" + detailed + "&key=" + Const.MAP_KEY);
        JSONObject jsonObj = JSONObject.parseObject(result);
        Object statusObject = jsonObj.get("status");
        Integer status = Integer.parseInt(String.valueOf(statusObject));
        if (status.equals(0)) {
            //根据groupId查询大商户
            Group group = groupMapper.selectByPrimaryKey(shopInDTO.getGroupId());
            JSONObject resultObject = jsonObj.getJSONObject("result");
            String title = resultObject.getString("title");
            JSONObject address_componentsObject = resultObject.getJSONObject("address_components");//地址详细信息
            JSONObject locationObject = resultObject.getJSONObject("location");//经纬度对象
            String province = address_componentsObject.getString("province");
            String city = address_componentsObject.getString("city");
            String district = address_componentsObject.getString("district");
            Double lng = locationObject.getDouble("lng");
            Double lat = locationObject.getDouble("lat");
            Userbase userbase = new Userbase();
            userbase.setBz("大商户创建门店");
            userbase.setGmtCreate(new Date());
            userbase.setGmtModified(new Date());
            userbase.setGroupId(shopInDTO.getGroupId());
            userbase.setIp(null);
            userbase.setLastLogin(null);
            userbase.setPassword(new SimpleHash("SHA-1", shopInDTO.getUsername(), shopInDTO.getPassword()).toString());
            userbase.setRights(null);//权限码默认为空
            userbase.setRoleId("0");
            userbase.setSkin("default");
            userbase.setStatus(UserStatus.Normal.getType());
            userbase.setUsername(shopInDTO.getUsername());
            userbase.setUserType(CommonEnum.UserType.Store.getType());
            userbaseMapper.insertKey(userbase);

            Shop shop = new Shop();
//            shop.setSettleAmount(shopInDTO.getSettleAmount()*100);
            shop.setSettleDay(shopInDTO.getSettleDay());
            shop.setMerchantName(shopInDTO.getMerchantName());//shopInDTO.getMerchantName()
            shop.setIndustry(shopInDTO.getIndustry());
            shop.setPrincipalName(shopInDTO.getPrincipalName());
            shop.setPrincipalMobile(shopInDTO.getPrincipalMobile());
            shop.setPhone(shopInDTO.getPhone());
            shop.setWorkTime(shopInDTO.getWorkTime());
            shop.setIcon(shopInDTO.getIcon());
            shop.setAddressProvince(province);// 省
            shop.setAddressCity(city);// 市
            shop.setAddressDistrict(district);// 区
//					shop.setAddress(title);
            shop.setAddress(shopInDTO.getAddress());
            shop.setMemo(shopInDTO.getMemo());
            shop.setLongitude(lng + "");
            shop.setLatitude(lat + "");
            shop.setBusinessLicense(shopInDTO.getBusinessLicense());
            shop.setQrImg(shopInDTO.getQrImg());
            shop.setRecieveAccountType(shopInDTO.getRecieveAccountType());
            shop.setMerchantFeeId(shopInDTO.getMerchantFeeId());
            shop.setAccountBank(shopInDTO.getAccountBank());
            shop.setRecieveBankNo(shopInDTO.getRecieveBankNo());//收款卡号开户行支行
            shop.setRecieveBank(shopInDTO.getRecieveBank());//收款银行
            shop.setRecieveName(shopInDTO.getRecieveName());
            shop.setUserId(userbase.getId());// 用户id
            shop.setGmtModified(new Date());
            shop.setStatus(1);
            shop.setGmtCreate(new Date());
            shop.setAccountArea(shopInDTO.getAccountArea());
            shop.setRecieveAccount(shopInDTO.getRecieveAccount());
            shop.setPersonId(shopInDTO.getPersonId());
            shop.setAlbumpics(shopInDTO.getAlbumpics());
            shop.setFinanceName(shopInDTO.getFinanceName());
            shop.setFinancePhone(shopInDTO.getFinancePhone());
            try {
                shopMapper.insert(shop);
            } catch (Exception e) {
                throw new ApplicationException(Rescode.FAIL, "门店数据保存异常");
            }

            String merName = shopInDTO.getMerchantName();//商户名称
            String corpType = "02";// 00三资企业 01合资企业 02民营企业 03国企 04私营企业
            String pubOrPri = null;
            String iDCardNo = null;
            String lineBankNum = "000000000000";//支行联行号
            String bankAccountNo = shopInDTO.getRecieveAccount();//结算银行卡号
            String bankAccountNm = shopInDTO.getRecieveName();
            String phone = shopInDTO.getPhone();
            String mobilePhone = shopInDTO.getPrincipalMobile();
            String groupId = group.getPayGroupCode();//大商户号
            //String corpId=UtilFun.formatNumber(shop.getId(), 8);//商户唯一编号
            String corpId = UtilFun.createRandomStr(2) + UtilFun.formatNumber(shop.getId(), 6);
            String bankCode = shopInDTO.getAccountBank();//结算银行行号
            String sonBankName = Tools.notEmpty(shopInDTO.getRecieveBankNo()) ? shopInDTO.getRecieveBankNo() : "default";//支行名称recieveBankNo
            Integer type = shopInDTO.getRecieveAccountType();
            String merLvl = shopInDTO.getMerchantFeeId();
            if (shopInDTO.getRecieveAccountType().equals(type)) {
                pubOrPri = "22";
                iDCardNo = "000000000000000000";//长度必须是18位
            } else if (shopInDTO.getRecieveAccountType().equals(type)) {
                pubOrPri = "11";
                iDCardNo = shopInDTO.getPersonId();
            }
            MerchantRegister merchantRegister = MerchantRegister.initialize(
                    corpId, merName, groupId, corpType, bankCode,
                    bankAccountNm, bankAccountNo, phone, mobilePhone, sonBankName,
                    lineBankNum, pubOrPri, iDCardNo, merLvl, detailed);
            PayResult payResult = IPayAPI.merchantRegister(merchantRegister);
            if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
            }
            //创建门店-商户关系
            ShopGroupRelation shopGroupRelation = new ShopGroupRelation();
            shopGroupRelation.setGmtCreate(new Date());
            shopGroupRelation.setGmtModified(new Date());
            shopGroupRelation.setShopId(shop.getId());
            shopGroupRelation.setGroupId(shopInDTO.getGroupId());
            shopGroupRelation.setAgentId(shopInDTO.getTagentId());//发展代理商ID
            shopGroupRelation.setPayMerchantCode(corpId);//支付平台商户号
            shopGroupRelation.setBalance(0L);
            shopGroupRelation.setLockBalanceEnc(new SimpleHash("SHA-1", "0", shopInDTO.getGroupId() + "").toString());//余额加密字段
            shopGroupRelation.setLockBalance(0L);
            shopGroupRelation.setLockBalanceEnc(new SimpleHash("SHA-1", "0", shopInDTO.getGroupId() + "").toString());//锁定金额密文
            shopGroupRelation.setVarturelCardno(null);//支付平台卡号 暂未返回
            shopGroupRelation.setType(1);
            shopGroupRelationMapper.insert(shopGroupRelation);
            //更新设备绑定门店
            Device device = deviceMapper.selectByPrimaryKey(shopInDTO.getDeviceId());
            if (device != null) {
                device.setShopId(shop.getId());
                try {
                    deviceMapper.updateByPrimaryKey(device);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ApplicationException(Rescode.FAIL, "设备保存异常");
                }
                return true;
            }
            //调用发送邮件，和调用短信
            try {
                templateMailSendService.sendMerchantCreateSms(shopInDTO.getGroupId(), shopInDTO.getPrincipalMobile(), shopInDTO.getUsername(), shopInDTO.getPassword());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        } else {
            throw new ApplicationException(Rescode.FAIL, "地理位置解析异常");

        }

    }

    @Override
    public AgentListOutDTO agentList(AgentInDTO agentInDTO) {
        ArrayList<AgentInfoOutDTO> list = agentMapper.findAgentList(agentInDTO);
        AgentListOutDTO agentListOutDTO = new AgentListOutDTO();
        agentListOutDTO.setAgentOutDTOList(list);
        return agentListOutDTO;
    }

    @Override
    public AgentListOutDTO agentList2(AgentInDTO agentInDTO) {
        ArrayList<AgentInfoOutDTO> list = agentMapper.findAgentList2(agentInDTO);
        AgentListOutDTO agentListOutDTO = new AgentListOutDTO();
        agentListOutDTO.setAgentOutDTOList(list);
        return agentListOutDTO;
    }


    @Override
    public ShopListOutDTO listShopCrcode(CrcodeInDTO shopCrcodeInDTO) throws ApplicationException {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        ArrayList<CrcodeOutDTO> shopCrcodeOutList = new ArrayList<CrcodeOutDTO>();
        switch (shopCrcodeInDTO.getType()) {
            case 2: //1用户自主注册 渠道发展 2表示代理商 3表示门店 4表示会员用户推广
                Agent agent = agentMapper.selectByPrimaryKey(shopCrcodeInDTO.getAgentId());
                Crcode crcode = new Crcode();
                crcode.setUserId(agent.getUserId());
                crcode.setType(2);
                List<Crcode> agentList = crcodeMapper.selectUserIdAll(crcode);
                for (Crcode Crcode : agentList) {
                    CrcodeOutDTO shopCrcodeOutDTO = new CrcodeOutDTO();
                    try {
                        PropertyCopyUtil.copyPropertiesExclude(Crcode, shopCrcodeOutDTO);
                    } catch (Exception e) {
                        throw new ApplicationException(Rescode.FAIL, "属性复制异常");
                    }
                    shopCrcodeOutList.add(shopCrcodeOutDTO);
                    shopListOutDTO.setCrcodeOutDTOList(shopCrcodeOutList);
                }
                shopListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
                break;
            case 3:
                Shop shop = shopMapper.selectByPrimaryKey(shopCrcodeInDTO.getShopId());
                Crcode crcodeShop = new Crcode();
                crcodeShop.setUserId(shop.getUserId());
                crcodeShop.setType(3);
                List<Crcode> ShopCrcodeList = crcodeMapper.selectUserIdAll(crcodeShop);
                for (Crcode Crcode : ShopCrcodeList) {
                    CrcodeOutDTO shopCrcodeOutDTO = new CrcodeOutDTO();
                    try {
                        PropertyCopyUtil.copyPropertiesExclude(Crcode, shopCrcodeOutDTO);
                    } catch (Exception e) {
                        throw new ApplicationException(Rescode.FAIL, "属性复制异常");
                    }
                    shopCrcodeOutList.add(shopCrcodeOutDTO);
                    shopListOutDTO.setCrcodeOutDTOList(shopCrcodeOutList);
                }
                shopListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
                break;
            default:
                break;
        }
        return shopListOutDTO;


    }


    @Override
    public Boolean saveShopCrcode(CrcodeInDTO shopInDTO) throws ApplicationException {
        //查询类型类代理商门店最大场景值
        Crcode crcode = crcodeMapper.findMaxsceneId();
        Integer sceneid = null;
        if (crcode == null) {
            sceneid = 1;
        } else {
            sceneid = crcode.getSceneid() + 1;
        }
        try {
            wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(shopInDTO.getGroupId()));
            WxMpQrCodeTicket ticket = this.wxService.getQrcodeService().qrCodeCreateLastTicket(sceneid);
            //压塑的网址
            String weixinurl = this.wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket(), true);
            File file = this.wxService.getQrcodeService().qrCodePicture(ticket);
            FileUploadContorller fileUploadContorller = new FileUploadContorller();
            String fileUrl = fileUploadContorller.upload(file, "/file/ebosService/crcode/shop/");
            Crcode shop_AgentCrcode = new Crcode();
            shop_AgentCrcode.setGmtCreate(new Date());
            shop_AgentCrcode.setGmtModified(new Date());
            shop_AgentCrcode.setQrcodeLinkUrl(weixinurl);//二维码链接URL
            shop_AgentCrcode.setQrcodeName(shopInDTO.getQrcodeName());
            shop_AgentCrcode.setQrcodePicurl(fileUrl);//二维码图片URL
            shop_AgentCrcode.setScanTimes(0);
            shop_AgentCrcode.setStatus(1);
            shop_AgentCrcode.setQrcode(null);
            switch (shopInDTO.getType()) {          //1用户自主注册 渠道发展 2表示代理商 3表示门店 4表示会员用户推广
                case 2:
                    Agent agent = agentMapper.selectByPrimaryKey(shopInDTO.getAgentId());
                    shop_AgentCrcode.setUserId(agent.getUserId());
                    shop_AgentCrcode.setType(BizEnum.MemberDevelopeFrom.AgentDevelope.getType());
                    break;
                case 3:
                    Shop shop = shopMapper.selectShopInfo(shopInDTO.getShopId(), shopInDTO.getGroupId());
                    shop_AgentCrcode.setUserId(shop.getUserId());
                    shop_AgentCrcode.setType(BizEnum.MemberDevelopeFrom.ShopDevelope.getType());
                    break;
                default:
                    break;
            }
            shop_AgentCrcode.setSceneid(sceneid);//场景值
            try {
                crcodeMapper.insert(shop_AgentCrcode);
            } catch (Exception e) {
                throw new ApplicationException(Rescode.FAIL, "创建二维码出现异常");
            }
            return true;
        } catch (Exception e) {
            throw new ApplicationException(Rescode.FAIL, "创建二维码接口出现异常");
        }
    }


    @Override
    public ShopOutDTO selectShopInfo(ShopInDTO shopInDTO) throws ApplicationException {
        ShopOutDTO shopOutDTO = new ShopOutDTO();
        Shop shop = null;
        try {
            shop = shopMapper.selectShopInfo(shopInDTO.getId(), shopInDTO.getGroupId());
        } catch (Exception e) {
            throw new ApplicationException(Rescode.FAIL, "查询详情异常");
        }
        try {
            PropertyCopyUtil.copyPropertiesExclude(shop, shopOutDTO);
        } catch (Exception e) {
            throw new ApplicationException(Rescode.FAIL, "属性复制异常");
        }
        shopOutDTO.setAgentName(shop.getAgent().getMerchantName());
        shopOutDTO.setTagentId(shop.getShopGroupRelation().getAgentId());
        shopOutDTO.setIndustryName(shop.getIndustryType().getName());
        shopOutDTO.setUserName(shop.getUserbase().getUsername());

        shopOutDTO.setMemberNum((shop.getStatisShop().getMemberNum() == null ? 0 : shop.getStatisShop().getMemberNum()));
        shopOutDTO.setSumAmount((shop.getStatisShop().getSumAmount() == null ? 0 : shop.getStatisShop().getSumAmount()));
        shopOutDTO.setSumOrderNum((shop.getStatisShop().getSumOrderNum() == null ? 0 : shop.getStatisShop().getSumOrderNum()));
        shopOutDTO.setSumProfit((shop.getStatisShop().getSumProfit() == null ? 0 : shop.getStatisShop().getSumProfit()));
        shopOutDTO.setThisAmount((shop.getStatisShop().getThisAmount() == null ? 0 : shop.getStatisShop().getThisAmount()));
        shopOutDTO.setThisOrderNum((shop.getStatisShop().getThisOrderNum() == null ? 0 : shop.getStatisShop().getThisOrderNum()));
        shopOutDTO.setThisProfit((shop.getStatisShop().getThisProfit() == null ? 0 : shop.getStatisShop().getThisProfit()));
        shopOutDTO.setShopAddress(shop.getAddressProvince() + "/" + shop.getAddressCity() + "/" + shop.getAddressDistrict());


        //此处门店余额查询 暂时直连支付平台
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
//        Date date = new Date();
//        String str = simpleDateFormat.format(date);
//        String orgTranDateTime = str;
//        Random random = new Random();
//        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
//        String orgOrderNum = str + rannum;//时间加随机数5位
//        String SysTraceNum = StringUtil.getRandNumberStr(12);//交易流水号12位
//        String UserId = shop.getShopGroupRelation().getPayMerchantCode() + "";
//
//        String GroupId = shop.getGroup().getPayGroupCode();
//        PayBalanceQuery payBalanceQuery = PayBalanceQuery.initialize(UserId, GroupId, SysTraceNum, orgTranDateTime, orgOrderNum);
//        PayBalanceResult payResult = IPayAPI.accountBalanceQuery(payBalanceQuery, true);
//        if (!PayBalanceResult.SUCCESS.equals(payResult.getRespCode())) {
//            throw new ApplicationException(Rescode.FAIL, payResult.getMsgExt());
//        }
//        //此处余额需要查询支付平台
//        if (Tools.notEmpty(payResult.getCurBal())) {
//            shopOutDTO.setBalance(Long.parseLong(payResult.getCurBal()));//余额
//        }
//        if (Tools.notEmpty(payResult.getCurBalB())) {
//            shopOutDTO.setLockBalance(Long.parseLong(payResult.getLockBal()));//锁定金额
//        }

        String UserId=shop.getShopGroupRelation().getPayMerchantCode()+"";
        String GroupId=shop.getGroup().getPayGroupCode();

        Wallet wallet=walletService.selectShopWallet(UserId, GroupId, shop.getUserId());
        //此处余额需要查询支付平台
//        map.put("balance",wallet.getCanBalance());//余额
//        map.put("feeBalance",wallet.getCanFreezeBalance());//锁定金额
        if(wallet !=null){
            shopOutDTO.setBalance(Long.parseLong(wallet.getCanBalance().toString()));//余额
            shopOutDTO.setLockBalance(Long.parseLong(wallet.getCanFreezeBalance().toString()));
            shopOutDTO.setCanLockBalance(Long.parseLong(wallet.getCanBalanceLocked().toString()));
        }



        shopOutDTO.setVarturelCardno(UserId);
        shopOutDTO.setAgentCreate(shop.getAgent().getGmtCreate());
        shopOutDTO.setAgentPhone(shop.getAgent().getPrincipalMobile());
        return shopOutDTO;
    }


    @Override
    public CrcodeOutDTO selectCrcode(Long id) throws ApplicationException {
        Crcode crcode = crcodeMapper.selectByPrimaryKey(id);
        if (crcode != null) {
            CrcodeOutDTO crcodeOutDTO = new CrcodeOutDTO();
            crcodeOutDTO.setQrcodeName(crcode.getQrcodeName());
            crcodeOutDTO.setId(crcode.getId());
            return crcodeOutDTO;
        }
        return null;
    }


    @Override
    public Boolean updateShopCrcode(CrcodeInDTO shopInDTO) throws ApplicationException {
        Crcode crcode = crcodeMapper.selectByPrimaryKey(shopInDTO.getId());
        if (crcode != null) {
            if (shopInDTO.getStatus() != null && shopInDTO.getStatus().equals(0)) {
                crcode.setStatus(0);
            } else {
                crcode.setQrcodeName(shopInDTO.getQrcodeName());
            }
            crcodeMapper.updateByPrimaryKey(crcode);
            return true;
        }
        return false;
    }


    @Override
    public AgentInfoOutDTO selectAgentName(ShopInDTO shopInDTO) throws ApplicationException {
        Agent agent = new Agent();
        AgentInfoOutDTO agentInfoOutDTO = new AgentInfoOutDTO();
        agent.setGroupId(shopInDTO.getGroupId());
        agent.setMerchantName(shopInDTO.getTagentName());
        Agent agentOut = agentMapper.selectByPrimaryMerchantName(agent);
        if (agentOut != null) {
            agentInfoOutDTO.setId(agentOut.getId());
        }
        return agentInfoOutDTO;
    }


    @Override
    public Boolean editShop(ShopInDTO shopInDTO) throws ApplicationException {
        //根据地址查询经纬度
        String detailed = shopInDTO.getProvinceCityDistrict() + shopInDTO.getAddress();
        String result = HttpClientUtil.get(Const.GEOCODER + "?=" + detailed + "&key=" + Const.MAP_KEY);
        JSONObject jsonObj = JSONObject.parseObject(result);
        Object statusObject = jsonObj.get("status");
        Integer status = Integer.parseInt(String.valueOf(statusObject));
        if (!status.equals(0)) {
            throw new ApplicationException(Rescode.FAIL, "地理位置解析异常,请检查区域管理地址的填写");
        }
        // throw new ApplicationException(Rescode.FAIL,"地理位置解析异常");
        //	  if(status.equals(0)){
        //根据groupId查询大商户
        Group group = groupMapper.selectByPrimaryKey(shopInDTO.getGroupId());
        JSONObject resultObject = jsonObj.getJSONObject("result");
        String title = resultObject.getString("title");
        JSONObject address_componentsObject = resultObject.getJSONObject("address_components");//地址详细信息
        JSONObject locationObject = resultObject.getJSONObject("location");//经纬度对象
        String lng = null;
        String lat = null;
        if (Tools.notEmpty(shopInDTO.getLongitude()) && Tools.notEmpty(shopInDTO.getLatitude())) {
            lng = shopInDTO.getLongitude();
            lat = shopInDTO.getLatitude();
        } else {
            lng = locationObject.getDouble("lng") + "";
            lat = locationObject.getDouble("lat") + "";
        }
        String province = address_componentsObject.getString("province");
        String city = address_componentsObject.getString("city");
        String district = address_componentsObject.getString("district");
        Shop shop = shopMapper.selectByPrimaryKey(shopInDTO.getId());
        Userbase userbase = userbaseMapper.selectByPrimaryKey(shop.getUserId());
        ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(userbase.getGroupId(), shop.getId());
        userbase.setBz("门店修改");
        userbase.setGmtCreate(new Date());
        userbase.setGmtModified(new Date());
        userbase.setGroupId(shopInDTO.getGroupId());
        userbase.setIp("");
        userbase.setLastLogin(null);
        if (Tools.notEmpty(shopInDTO.getPassword())) {
            userbase.setPassword(new SimpleHash("SHA-1", shopInDTO.getUsername(), shopInDTO.getPassword()).toString());
        }
        userbase.setRights("");//权限码默认为空
        userbase.setRoleId("0");
        userbase.setSkin("default");
        userbase.setStatus(UserStatus.Normal.getType());
        userbase.setUsername(shopInDTO.getUsername());
        userbase.setUserType(CommonEnum.UserType.Store.getType());
        userbase.setId(shop.getUserId());
        userbaseMapper.updateByPrimaryKeySelective(userbase);
        shop.setSettleDay(shopInDTO.getSettleDay());
//        shop.setSettleAmount(shopInDTO.getSettleAmount()*100);
        shop.setMerchantName(shopInDTO.getMerchantName());//shopInDTO.getMerchantName()
        shop.setIndustry(shopInDTO.getIndustry());
        shop.setPrincipalName(shopInDTO.getPrincipalName());
        shop.setPrincipalMobile(shopInDTO.getPrincipalMobile());
        shop.setPhone(shopInDTO.getPhone());
        shop.setWorkTime(shopInDTO.getWorkTime());
        shop.setIcon(shopInDTO.getIcon());
        shop.setAddressProvince(province);// 省
        shop.setAddressCity(city);// 市
        shop.setAddressDistrict(district);// 区
//					shop.setAddress(title);
        shop.setAddress(shopInDTO.getAddress());
        shop.setMemo(shopInDTO.getMemo());
        shop.setLongitude(lng);
        shop.setLatitude(lat);
        shop.setBusinessLicense(null);
        shop.setRecieveAccountType(shopInDTO.getRecieveAccountType());
        shop.setMerchantFeeId(shopInDTO.getMerchantFeeId());
        shop.setAccountBank(shopInDTO.getAccountBank());
        shop.setRecieveBankNo(shopInDTO.getRecieveBankNo());//收款卡号开户行支行
        shop.setRecieveBank(null);//收款银行
        shop.setRecieveName(shopInDTO.getRecieveName());
        shop.setUserId(userbase.getId());// 用户id
        shop.setGmtModified(new Date());
        shop.setStatus(1);
        shop.setGmtCreate(shop.getGmtCreate());
        shop.setAccountArea(shopInDTO.getAccountArea());
        shop.setRecieveAccount(shopInDTO.getRecieveAccount());
        shop.setPersonId(shopInDTO.getPersonId());
        shop.setBusinessLicense(shopInDTO.getBusinessLicense());
        shop.setQrImg(shopInDTO.getQrImg());
        shop.setFinanceName(shopInDTO.getFinanceName());
        shop.setFinancePhone(shopInDTO.getFinancePhone());
        try {
            shopMapper.updateByPrimaryKey(shop);
        } catch (Exception e) {
            throw new ApplicationException(Rescode.FAIL, "修改数据出现异常");
        }

        String merName = shopInDTO.getMerchantName();//商户名称
        String corpType = "02";// 00三资企业 01合资企业 02民营企业 03国企 04私营企业
        String pubOrPri = null;
        String iDCardNo = null;
        String lineBankNum = "000000000000";//支行联行号
        String bankAccountNo = shopInDTO.getRecieveAccount();//结算银行卡号
        String bankAccountNm = shopInDTO.getRecieveName();
        String phone = shopInDTO.getPhone();
        String mobilePhone = shopInDTO.getPrincipalMobile();
        String groupId = group.getPayGroupCode();//大商户号
        String corpId = shopGroupRelation.getPayMerchantCode();
        String bankCode = shopInDTO.getAccountBank();//结算银行行号
        String sonBankName = Tools.notEmpty(shopInDTO.getRecieveBankNo()) ? shopInDTO.getRecieveBankNo() : "default";//支行名称recieveBankNo

        Integer type = shopInDTO.getRecieveAccountType();
        String merLvl = shopInDTO.getMerchantFeeId();
        String merStat = "00";
        if (shopInDTO.getRecieveAccountType().equals(type)) {
            pubOrPri = "22";
            iDCardNo = "000000000000000000";//长度必须是18位
        } else if (shopInDTO.getRecieveAccountType().equals(type)) {
            pubOrPri = "11";
            iDCardNo = shopInDTO.getPersonId();
        }
        MerchantUpdate merchantUpdate = MerchantUpdate.initialize(
                corpId, merName, groupId, corpType, bankCode,
                bankAccountNm, bankAccountNo, phone, mobilePhone, sonBankName,
                lineBankNum, pubOrPri, iDCardNo, merLvl, detailed, merStat);
        PayResult payResult = IPayAPI.merchantUpdate(merchantUpdate);
        if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
            throw new ApplicationException(Rescode.FAIL, payResult.getRespCode() + "#" + payResult.getMsgTxt());
        }
        return true;

    }

    @Override
    public Boolean editShopAccount(ShopInDTO shopInDTO) throws ApplicationException {

        Shop shop = new Shop();
        shop.setId(shopInDTO.getId());
        shop.setRecieveAccountType(shopInDTO.getRecieveAccountType());
        shop.setAccountBank(shopInDTO.getAccountBank());
        shop.setRecieveBankNo(shopInDTO.getRecieveBankNo());//收款卡号开户行支行
//        shop.setRecieveBank(shopInDTO.getRecieveBank());//收款银行
        shop.setRecieveName(shopInDTO.getRecieveName());
        shop.setGmtModified(new Date());
        shop.setAccountArea(shopInDTO.getAccountArea());
        shop.setRecieveAccount(shopInDTO.getRecieveAccount());
        shop.setFinanceName(shopInDTO.getFinanceName());
        shop.setFinancePhone(shopInDTO.getFinancePhone());
        shop.setPersonId(shopInDTO.getPersonId());
        try {
            shopMapper.updateByPrimaryKeySelective(shop);
        } catch (Exception e) {
            throw new ApplicationException(Rescode.FAIL, "修改数据出现异常");
        }


        return true;

    }


    @Override
    public GroupListOutDTO GroupList() throws ApplicationException {
        GroupListOutDTO groupListOutDTO = new GroupListOutDTO();
        ArrayList<GroupOutDTO> groupOutList = new ArrayList<GroupOutDTO>();
        List<Group> grouplist = groupMapper.selectAll();
        for (Group group : grouplist) {
            GroupOutDTO groupOutDTO = new GroupOutDTO();
            try {
                PropertyCopyUtil.copyPropertiesExclude(group, groupOutDTO);
                groupOutList.add(groupOutDTO);
                groupListOutDTO.setGroupOutDTOList(groupOutList);
            } catch (Exception e) {
                throw new ApplicationException(Rescode.FAIL, "属性复制异常");
            }
        }
        return groupListOutDTO;
    }

    @Override
    public void updateShop(Shop shop) throws ApplicationException {
        shopMapper.updateShop(shop.getId());
    }

    @Override
    public ShopListOutDTO listGroupShop(Long groupId) {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        List<ShopOutDTO> shopOutDTOList = shopMapper.listGroupShop(groupId);
        shopListOutDTO.setShopOutDTOList(shopOutDTOList);
        shopListOutDTO.setErrorCode(Rescode.SUCCESS);
        return shopListOutDTO;
    }

    @Override
    public ShopListOutDTO listAgentShop(Long groupId, Long agentId) {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        List<ShopOutDTO> shopOutDTOList = shopMapper.listAgentShop(groupId, agentId);
        shopListOutDTO.setShopOutDTOList(shopOutDTOList);
        shopListOutDTO.setErrorCode(Rescode.SUCCESS);
        return shopListOutDTO;
    }


    @Override
    public BaseOutDTO updateShopState(ShopInDTO shopInDTO) throws ApplicationException {
        //Shop shop=shopMapper.selectByPrimaryKey(shopInDTO.getId());
        Shop shop = new Shop();
        shop.setId(shopInDTO.getId());
        shop.setGmtModified(new Date());
        BaseOutDTO baseOutDTO = new BaseOutDTO();
        if (shop != null) {
            shop.setStatus(shopInDTO.getStatus());
            shopMapper.updateByPrimaryKeySelective(shop);
            Shop shopr = shopMapper.selectByPrimaryKey(shopInDTO.getId());
            //修改门店账号状态
            Userbase ub = new Userbase();
            ub.setId(shopr.getUserId());
            ub.setStatus(shopInDTO.getStatus());
            userbaseMapper.updateStatusByKey(ub);
            if (shopInDTO.getStatus() == 0) {
                baseOutDTO.setErrorCode(Rescode.SUCCESS, "启动");
            } else if (shopInDTO.getStatus() == 1) {
                baseOutDTO.setErrorCode(Rescode.SUCCESS, "禁用");
            }
        } else {
            baseOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "修改失败");
        }
        return baseOutDTO;
    }


    @Override
    public CheckOutDTO checkYsShop(ShopInDTO shopInDTO) {
        CheckOutDTO checkOutDTO = new CheckOutDTO();
        checkOutDTO.setErrorCode(Rescode.SUCCESS);
        Shop shop = shopMapper.selectByPrimaryKey(shopInDTO.getId());
        if (shop != null && new Integer(51).equals(shop.getSubIndustry())) {
            checkOutDTO.setResult(1);
        } else {
            checkOutDTO.setResult(0);
        }
        return checkOutDTO;
    }


    @Override
    public Boolean addBalance(BalanceInDTO balanceInDTO) throws ApplicationException {
        Integer tranAmt = Integer.valueOf(balanceInDTO.getTranAmt()) * 100;
        Long shopId = balanceInDTO.getId();
        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        Group group = groupMapper.selectByPrimaryKey(balanceInDTO.getGroupId());
        ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(balanceInDTO.getGroupId(), shopId);
        String OrgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmss");
        PayBalanceChange payBalanceChange = PayBalanceChange.initialize(group.getPayGroupCode(),
                shopGroupRelation.getPayMerchantCode(), tranAmt + "", "1",
                OrgOrderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), StringUtil.getRandNumberStr(10), "156");
        PayResult payResult = IPayAPI.consumptionBalanceChangeMerchant(payBalanceChange);
        if (!payResult.getRespCode().equals("0000")) {
            throw new ApplicationException(Rescode.FAIL, "商户修改余额失败");
        }

        //插入线下交易表
        TradeOffline tradeOffline = new TradeOffline();
        tradeOffline.setGmtCreate(new Date());
        tradeOffline.setGmtModified(new Date());
        tradeOffline.setGroupId(group.getId());
        tradeOffline.setOrderId(OrgOrderNum);
        tradeOffline.setPayerId(group.getId());
        tradeOffline.setPayerName(group.getMerchantName());
        tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
        tradeOffline.setReceiverId(shopId + "");
        tradeOffline.setReceiverName(shop.getMerchantName());
        tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        tradeOffline.setOrderAmount(tranAmt);
        tradeOffline.setRealAmount(tranAmt);
        tradeOffline.setMemo("大商户修改余额");
        tradeOffline.setDetail("大商户修改余额");
        tradeOffline.setDividableAmount(0);// 可分润金额
        tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.CalculateFinished.getType());
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.AddBalance.getType());// 交易类型
        tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOffline.setIsWallet(Boolean.TRUE);
        tradeOffline.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());
        tradeOffline.setPayType((byte) BizEnum.PaymentType.Other.getType());//支付方式
        int result = tradeOfflineMapper.insertSelective(tradeOffline);
        return true;
    }

    @Override
    public ShopCashierListOutDTO listShopCashier(ShopCashierInDTO shopCashierInDTO, Page page) {
        ShopCashierListOutDTO shopCashierListOutDTO = new ShopCashierListOutDTO();

        Userbase userbase = new Userbase();
        userbase.setName(shopCashierInDTO.getName());
        userbase.setGroupId(shopCashierInDTO.getShopId());    //注意 如果用户是收银员类型则groupId字段保存门店ID

        userbase.setPage(page);

        List<ShopCashierInDTO> shopCashierInDTOList = userbaseMapper.listPageShopCashier(userbase);
        shopCashierListOutDTO.setShopCashierInDTOList(shopCashierInDTOList);
        shopCashierListOutDTO.setPage(page);
        shopCashierListOutDTO.setErrorCode(Rescode.SUCCESS);
        return shopCashierListOutDTO;
    }

    @Override
    public BaseOutDTO addShopCashier(ShopCashierInDTO shopCashierInDTO) {
        BaseOutDTO baseOutDTO = new BaseOutDTO();
        Date date = new Date();

        Userbase userbase = userbaseMapper.selectByUsernameAndGroupId(shopCashierInDTO.getUsername(), shopCashierInDTO.getShopId());
        if (userbase == null) {
            userbase = new Userbase();
            userbase.setUsername(shopCashierInDTO.getUsername());
            userbase.setPassword(shopCashierInDTO.getPassword());
            userbase.setPhone(shopCashierInDTO.getPhone());
            userbase.setName(shopCashierInDTO.getName());
            userbase.setGroupId(shopCashierInDTO.getShopId());
            userbase.setUserType(CommonEnum.UserType.Cashier.getType());
            userbase.setGmtModified(date);
            userbase.setGmtCreate(date);
            userbase.setStatus(1);
            userbaseMapper.insertSelective(userbase);
            baseOutDTO.setErrorCode(Rescode.SUCCESS);
        } else {
            baseOutDTO.setErrorCode(Rescode.FAIL);
            baseOutDTO.setErrorMsg("登录账户已存在");
        }

        return baseOutDTO;
    }

    @Override
    public BaseOutDTO changeStatus(ShopCashierInDTO shopCashierInDTO) {
        BaseOutDTO baseOutDTO = new BaseOutDTO();
        Userbase userbase = new Userbase();
        userbase.setId(shopCashierInDTO.getId());
        if (shopCashierInDTO.getStatus() != null) {
            userbase.setStatus(Integer.parseInt(shopCashierInDTO.getStatus()));
        }
        if (shopCashierInDTO.getPassword() != null) {
            userbase.setPassword(shopCashierInDTO.getPassword());
        }
        userbaseMapper.updateByPrimaryKeySelective(userbase);
        baseOutDTO.setErrorCode(Rescode.SUCCESS);
        return baseOutDTO;
    }

    @Override
    public Map getShopDetailById(Long shopid) {
        return shopMapper.getShopDetailById(shopid);
    }

    @Override
    public Shop getShopIdByUserId(Long userid) {
        return shopMapper.selectUserId(userid);
    }


    @Override
    public Boolean saveAgentNetIn(AgentNetInDTO agentNetInDTO) throws ApplicationException {

        //判断这个账号有存在的代理商
        int count = userbaseMapper.queryUsernameByName(agentNetInDTO.getUsername());
        if (count != 0) {
            throw new ApplicationException(Rescode.FAIL, "登入账户名存在相同的请从新输入登入账户");
        }

        //根据地址查询经纬度
        String detailed = agentNetInDTO.getProvinceCityDistrict().replaceAll(" ", "") + agentNetInDTO.getAddress();
        String result = HttpClientUtil.get(Const.GEOCODER + "?=" + detailed + "&key=" + Const.MAP_KEY);
        JSONObject jsonObj = JSONObject.parseObject(result);
        Object statusObject = jsonObj.get("status");
        Integer status = Integer.parseInt(String.valueOf(statusObject));
        if (status.equals(0)) {
            //根据groupId查询大商户
            Group group = groupMapper.selectByPrimaryKey(agentNetInDTO.getGroupId());
            JSONObject resultObject = jsonObj.getJSONObject("result");
            String title = resultObject.getString("title");
            JSONObject address_componentsObject = resultObject.getJSONObject("address_components");//地址详细信息
            JSONObject locationObject = resultObject.getJSONObject("location");//经纬度对象
            String province = address_componentsObject.getString("province");
            String city = address_componentsObject.getString("city");
            String district = address_componentsObject.getString("district");
            Double lng = locationObject.getDouble("lng");
            Double lat = locationObject.getDouble("lat");
            Userbase userbase = new Userbase();
            userbase.setBz("大商户创建门店");
            userbase.setGmtCreate(new Date());
            userbase.setGmtModified(new Date());
            userbase.setGroupId(agentNetInDTO.getGroupId());
            userbase.setIp(null);
            userbase.setLastLogin(null);
            userbase.setPassword(new SimpleHash("SHA-1", agentNetInDTO.getUsername(), agentNetInDTO.getPassword()).toString());
            userbase.setRights(null);//权限码默认为空
            userbase.setRoleId("0");
            userbase.setSkin("default");
            userbase.setStatus(UserStatus.Stop.getType());//代理商入网开户
            userbase.setUsername(agentNetInDTO.getUsername());
            userbase.setUserType(CommonEnum.UserType.Store.getType());
            userbaseMapper.insertKey(userbase);

            Shop shop = new Shop();
            shop.setMerchantName(agentNetInDTO.getMerchantName());//shopInDTO.getMerchantName()
            shop.setIndustry(agentNetInDTO.getIndustry());
            shop.setPrincipalName(agentNetInDTO.getPrincipalName());
            shop.setPrincipalMobile(agentNetInDTO.getPrincipalMobile());
            shop.setPhone(agentNetInDTO.getPhone());
            shop.setWorkTime(agentNetInDTO.getWorkTime());
            shop.setIcon(agentNetInDTO.getIcon());
            shop.setAddressProvince(province);// 省
            shop.setAddressCity(city);// 市
            shop.setAddressDistrict(district);// 区
//			shop.setAddress(null);
            shop.setAddress(agentNetInDTO.getAddress());
            shop.setMemo(agentNetInDTO.getMemo());
            shop.setLongitude(lng + "");
            shop.setLatitude(lat + "");
            shop.setBusinessLicense(agentNetInDTO.getBusinessLicense());
            shop.setQrImg(agentNetInDTO.getQrImg());
            shop.setRecieveAccountType(agentNetInDTO.getRecieveAccountType());
            shop.setMerchantFeeId(agentNetInDTO.getMerchantFeeId());
            shop.setAccountBank(agentNetInDTO.getAccountBank());
            shop.setRecieveBankNo(agentNetInDTO.getRecieveBankNo());//收款卡号开户行支行
            shop.setRecieveBank(agentNetInDTO.getRecieveBank());//收款银行
            shop.setRecieveName(agentNetInDTO.getRecieveName());
            shop.setUserId(userbase.getId());// 用户id
            shop.setGmtModified(new Date());
            shop.setStatus(0);
            shop.setGmtCreate(new Date());

            //代理商入网时候银行卡开 页面没有省 在门店列表查看编辑时没有省不回显
            String accountArea = agentNetInDTO.getAccountArea().replaceAll(" ", "/");
            int beginIndexOf = accountArea.indexOf("/");
            StringBuilder sb = new StringBuilder(accountArea);
            sb.insert(beginIndexOf, "省");
            shop.setAccountArea(sb.toString());

//			shop.setAccountArea(agentNetInDTO.getAccountArea().replaceAll(" ","/"));

            shop.setRecieveAccount(agentNetInDTO.getRecieveAccount());
            shop.setPersonId(agentNetInDTO.getPersonId());
            shop.setAlbumpics(null);
//			shop.setAlbumpics(agentNetInDTO.getAlbumpics());
            shop.setFinanceName(agentNetInDTO.getFinanceName());
            shop.setFinancePhone(agentNetInDTO.getFinancePhone());
            try {
                shopMapper.insert(shop);
            } catch (Exception e) {
                throw new ApplicationException(Rescode.FAIL, "门店数据保存异常");
            }

            String merName = agentNetInDTO.getMerchantName();//商户名称
            String corpType = "02";// 00三资企业 01合资企业 02民营企业 03国企 04私营企业
            String pubOrPri = null;
            String iDCardNo = null;
            String lineBankNum = "000000000000";//支行联行号
            String bankAccountNo = agentNetInDTO.getRecieveAccount();//结算银行卡号
            String bankAccountNm = agentNetInDTO.getRecieveName();
            String phone = agentNetInDTO.getPhone();
            String mobilePhone = agentNetInDTO.getPrincipalMobile();
            String groupId = group.getPayGroupCode();//大商户号
            //String corpId=UtilFun.formatNumber(shop.getId(), 8);//商户唯一编号
            String corpId = UtilFun.createRandomStr(2) + UtilFun.formatNumber(shop.getId(), 6);
            String bankCode = agentNetInDTO.getAccountBank();//结算银行行号
            String sonBankName = agentNetInDTO.getRecieveBankNo();//支行名称recieveBankNo
            Integer type = agentNetInDTO.getRecieveAccountType();
            String merLvl = agentNetInDTO.getMerchantFeeId();
            if (agentNetInDTO.getRecieveAccountType().equals(type)) {
                pubOrPri = "22";
                iDCardNo = "000000000000000000";//长度必须是18位
            } else if (agentNetInDTO.getRecieveAccountType().equals(type)) {
                pubOrPri = "11";
                iDCardNo = agentNetInDTO.getPersonId();
            }
            MerchantRegister merchantRegister = MerchantRegister.initialize(
                    corpId, merName, groupId, corpType, bankCode,
                    bankAccountNm, bankAccountNo, phone, mobilePhone, sonBankName,
                    lineBankNum, pubOrPri, iDCardNo, merLvl, detailed);
            PayResult payResult = IPayAPI.merchantRegister(merchantRegister);
            if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
            }
            //创建门店-商户关系
            ShopGroupRelation shopGroupRelation = new ShopGroupRelation();
            shopGroupRelation.setGmtCreate(new Date());
            shopGroupRelation.setGmtModified(new Date());
            shopGroupRelation.setShopId(shop.getId());
            shopGroupRelation.setGroupId(agentNetInDTO.getGroupId());
            shopGroupRelation.setAgentId(agentNetInDTO.getTagentId());//发展代理商ID
            shopGroupRelation.setPayMerchantCode(corpId);//支付平台商户号
            shopGroupRelation.setBalance(0L);
            shopGroupRelation.setLockBalanceEnc(new SimpleHash("SHA-1", "0", agentNetInDTO.getGroupId() + "").toString());//余额加密字段
            shopGroupRelation.setLockBalance(0L);
            shopGroupRelation.setLockBalanceEnc(new SimpleHash("SHA-1", "0", agentNetInDTO.getGroupId() + "").toString());//锁定金额密文
            shopGroupRelation.setVarturelCardno(null);//支付平台卡号 暂未返回
            shopGroupRelation.setType(1);
            shopGroupRelationMapper.insert(shopGroupRelation);
            //更新设备绑定门店
            /*Device device=deviceMapper.selectByPrimaryKey(shopInDTO.getDeviceId());
			if(device!=null){
				device.setShopId(shop.getId());
				try {
					deviceMapper.updateByPrimaryKey(device);
				} catch (Exception e) {
					e.printStackTrace();
					throw new ApplicationException(Rescode.FAIL,"设备保存异常");
				}
				return true;
			}*/
            //调用发送邮件，和调用短信
//			try {
//				templateMailSendService.sendMerchantCreateSms(agentNetInDTO.getGroupId(),agentNetInDTO.getPrincipalMobile(), agentNetInDTO.getUsername(), agentNetInDTO.getPassword());
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
            return true;
        } else {
            throw new ApplicationException(Rescode.FAIL, "地理位置解析异常");

        }

    }


    @Override
    public ShopListOutDTO shopSelect(ShopSelectQueryDTO shopSelectQueryDTO) {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        Long total = shopMapper.countShopSelect(shopSelectQueryDTO);
        shopListOutDTO.setTotal(total);
        List<ShopOutDTO> shopOutDTOList = shopMapper.shopSelectList(shopSelectQueryDTO);
        shopListOutDTO.setShopOutDTOList(shopOutDTOList);
        shopListOutDTO.setErrorCode(Rescode.SUCCESS);
        return shopListOutDTO;
    }

    @Override
    public ShopListOutDTO selectShopList(ShopSelectQueryDTO shopSelectQueryDTO) throws Exception {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        List<ShopOutDTO> shopOutDTOList = shopMapper.shopSelectList(shopSelectQueryDTO);
        shopListOutDTO.setShopOutDTOList(shopOutDTOList);
        shopListOutDTO.setErrorCode(Rescode.SUCCESS);
        return shopListOutDTO;
    }

    @Override
    public MemberOutDTO queryShopAmount(ShopInDTO shopInDTO) throws ApplicationException {

        Group group = groupMapper.selectPayCodeById(shopInDTO.getGroupId());
        Shop shop = shopMapper.queryShop(shopInDTO.getGroupId(),shopInDTO.getId());

        String UserId=shop.getPayMerchantCode();
        String GroupId=group.getPayGroupCode();

        Wallet wallet=walletService.selectShopWallet(UserId, GroupId, shop.getUserId());
        MemberOutDTO memberOutDTO = new MemberOutDTO();
        memberOutDTO.setCurBal(wallet.getCanBalance()+"");
        memberOutDTO.setCurBalB(wallet.getNocanBalance()+"");
        memberOutDTO.setLockBal((wallet.getCanBalanceLocked()+wallet.getCanFreezeBalance())+"");
        memberOutDTO.setLockBalB((wallet.getNocanBalanceLocked()+wallet.getNocanFreezeBalance())+"");
        memberOutDTO.setPhone(group.getPrincipalMobile());
        memberOutDTO.setVirtualCard(shop.getPayMerchantCode());
        return memberOutDTO;
    }

    @Override
    public MemberOutDTO addShopBalance(BalanceInDTO balanceInDTO, String root_home_url) throws ApplicationException {
        MemberOutDTO memberOutDTO = new MemberOutDTO();
        Integer tranAmt = Integer.valueOf(balanceInDTO.getTranAmt()) * 100;
        Shop shop = shopMapper.queryShop(balanceInDTO.getGroupId(),balanceInDTO.getId());
        Group group=groupMapper.selectPayCodeById(balanceInDTO.getGroupId());
        String orgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmss");
        Date date = new Date();
        TradeOffline trade = new TradeOffline();
        trade.setGmtCreate(date);
        trade.setGmtModified(date);
        trade.setGroupId(group.getId());
        trade.setOrderId(orgOrderNum);
        trade.setPayerId(group.getId());// 付款者id号
        trade.setPayerName(group.getMerchantName());// 付款者姓名
        trade.setPayerType((byte) CommonEnum.UserType.User.getType());
        trade.setPayType((byte) BizEnum.PaymentType.Wallet.getType());// 支付方式
        // 生成订单支付方式未知
        trade.setReceiverId(null);// 接收者id
        trade.setReceiverName(null);// 接收者 此处以核销录入数据
        trade.setTransactionType((byte) BizEnum.TransactionType.AddBalanceMerchant.getType());// 交易类型
        trade.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        trade.setOrderAmount(tranAmt); // 订单金额
        trade.setDiscountAmount(0);// 折扣金额
        trade.setRealAmount(tranAmt);// 实付金额
        trade.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
        trade.setIsWallet(false);
        trade.setGoodType(null);// 商品类型(线上用) ？
        trade.setMemo(Tools.notEmpty(balanceInDTO.getRemark())?balanceInDTO.getRemark():"大商户修改代理商余额");
        trade.setDetail(Tools.notEmpty(balanceInDTO.getRemark())?balanceInDTO.getRemark():"大商户修改代理商余额");
        trade.setMerchantNo(null);// 商户号(对账用)
        trade.setTerminalNo(null);// 商户终端号
        trade.setPayAccount("");// 支付卡号
        trade.setScanOrganization(null);// 扫码付入网机构
        trade.setCrcodeStr(null);
        trade.setOldOrderId(null);
        trade.setDividableAmount(0);// 可分润金额
        trade.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        trade.setPayOrderid(orgOrderNum);
        trade.setPayBakOrderid(null);
        trade.setInNetCompany(null);// 入网机构
        tradeOfflineMapper.insertSelective(trade);
        PayResult flag=walletService.updateUserLockedAmount(shop.getPayMerchantCode(), group.getPayGroupCode(), shop.getUserId(), tranAmt+"", "1", 0,orgOrderNum);
        if (flag!=null) {
            // 增加余额成功
            memberOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
            logger.info("--余额增加成功--");
//            // 云流消息发送
//            if (Tools.notEmpty(member.getThirdUserId())) {
//                try {
//                    wxApiWalletServiceService.updatefinishSendMessage(orgOrderNum, UserAuthApi.MC_BLANCE_CHANGE);
//                } catch (Exception e) {
//                    logger.info("--云流消息发送异常--");
//                }
//            }else if(Tools.notEmpty(member.getOpenid())){
//                //微信发送模板消息
//                try {
//                    templateMailSendService.sendTemplate(trade,  BizEnum.WebTemplateType.template13.getType(), trade.getPayerId(),
//                            trade.getGroupId(), BizEnum.PaymentType.WebChat.getType(),rootHomeUrl);
//                } catch (Exception e) {
//                    logger.info ("模板消息发送失败"+e);
//                }
//
//            }
            return memberOutDTO;
        } else {
            throw new ApplicationException(Rescode.FAIL, "余额变化失败");
        }

    }

    @Override
    public GroupOutDTO getShopNameById(Long shopId) throws Exception {
        GroupOutDTO groupOutDTO = new GroupOutDTO();
        Shop shop= shopMapper.selectByPrimaryKey(shopId);
        groupOutDTO.setMerchantName(shop.getMerchantName());
        return groupOutDTO;
    }

    @Override
    public Response getShopByName(Long groupId, String shopName) throws ApplicationException {
        ShopListOutDTO shopListOutDTO = new ShopListOutDTO();
        ShopSelectQueryDTO shopSelectQueryDTO = new ShopSelectQueryDTO();

        shopSelectQueryDTO.setGroupId(groupId);
        shopSelectQueryDTO.setShopName(shopName);

        try {
            List<ShopOutDTO> shopOutDTOList=shopMapper.getShopByName(shopSelectQueryDTO);
            if(shopOutDTOList != null && shopOutDTOList.size()>0){
                shopListOutDTO.setShopOutDTOList(shopOutDTOList);
                return Response.getSuccess(shopListOutDTO);
            }else{
                return Response.getError("未查询到该门店");
            }
        } catch (Exception e) {
            return Response.getError("门店查询失败");
        }
    }

    @Override
    public List<Long> getAgentShopList(ShopSelectQueryDTO shopSelectQueryDTO) throws Exception {
        try {
            List<Shop> shopList = shopMapper.getAgentShopList(shopSelectQueryDTO);
            List<Long> shopListIdS = new ArrayList<Long>();
            if(shopList!=null && shopList.size()>0){
                for(int i=0;i<shopList.size();i++){
                    /*shopListIdS.set(i,shopList.get(i).getId());
                    shopListIdS.add(i,shopList.get(i).getId());*/
                    shopListIdS.add(shopList.get(i).getId());
                }
                return shopListIdS;
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException(Rescode.FAIL, "代理商直属门店查询系统异常");
        }
    }


}
